package com.zzj.controller;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.UUID;

@Controller
@RequestMapping("/f")
public class FileController {

    // 文件上传
    @RequestMapping("upload")
    public String fileUpload(MultipartFile file,String desc){
        System.out.println("desc = " + desc);
        String filename = file.getOriginalFilename();
        // 获取文件的后缀名
        String suffix = filename.substring(filename.lastIndexOf("."));
        System.out.println("suffix = " + suffix);
        String fileName = UUID.randomUUID() + suffix;
        // 生成新的文件名
        File file1 = new File("F://upload");
        if (!file1.exists()){
            file1.mkdir();
        }
        try {
            file.transferTo(new File(file1,fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "ok";
    }

    // 文件下载
    @RequestMapping("/down")
    public ResponseEntity<byte[]> fileDownload(String filename){
        String path = "F://upload";
        System.out.println("filename = " + filename);
        File file = new File(path, filename);
        try {
            String isoFilename=new String(filename.getBytes(StandardCharsets.UTF_8),StandardCharsets.ISO_8859_1);
            HttpHeaders headers = new HttpHeaders();
            // 以附件的形式发送
            headers.setContentDispositionFormData("attachment",isoFilename);
            // 流类型
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            return new ResponseEntity<>(FileUtils.readFileToByteArray(file),headers,HttpStatus.OK);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
